package com.microservice.auth.jwt.handler;

import cn.hutool.json.JSONUtil;
import com.microservice.core.domain.AjaxResult;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AccessDeniedHandler 是 Spring Security 中的一个接口，用于处理访问被拒绝的情况。当用户尝试访问受保护的资源但没有足够的权限时，
 * Spring Security 会调用 AccessDeniedHandler 来处理这种情况
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        AjaxResult ajaxResult = AjaxResult.error("拒绝访问："+e.getMessage());

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(ajaxResult).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
